package com.ncloud.crm.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.entity.order.WorkAttr;
import com.ncloud.crm.mapper.WorkAttrMapper;
import com.ncloud.crm.service.WorkAttrService;
import com.ncloud.crm.utils.ItemInfoUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;
import com.ncloud.param.service.SequenceService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WorkAttrServiceImpl implements WorkAttrService {
	
	private static final Logger logger = LogManager.getLogger(WorkAttrServiceImpl.class);
	
	@Autowired
	private WorkAttrMapper workAttrMapper;
	@Reference
	private SequenceService sequenceService;


	public JSONArray getId(JSONObject json) {
		if(json==null || !json.containsKey("workId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		List<WorkAttr> orderAttrs = workAttrMapper.getWorkAttrByWorkId(json.getLong("workId"));
		return JSON.parseArray(JSON.toJSONString(orderAttrs));
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		JSONObject object = new JSONObject();
		JSONArray itemArray = new JSONArray();
		if(json == null){
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}
		if(json.containsKey(OrderNodeDefineUtils.WORK_ITEM)){
			JSONObject item = json.getJSONObject(OrderNodeDefineUtils.WORK_ITEM);
			JSONObject param = new JSONObject();
			param.put(TableIdDefineUtils.WORK_ID,result.getLong(TableIdDefineUtils.WORK_ID));
			param.put("modifyTag",item.getString("modifyTag"));
			itemArray = ItemInfoUtils.getProjectAttr(item,param,"0");
		}
		object.put(OrderNodeDefineUtils.ORDER_ITEM,itemArray);
		return object;
	}

	@Override
	public JSONObject insert(JSONObject json) {

		WorkAttr orderAttr = JSON.parseObject(json.toJSONString(),WorkAttr.class);
		try {
			validation(orderAttr);
			workAttrMapper.insertWorkAttr(orderAttr);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}
	private void validation(WorkAttr workAttr){
		if(workAttr.getAttrId() == null){
			Long id = sequenceService.getSequence("seq_item_id");
			workAttr.setAttrId(id);
		}
	}

	@Override
	public List<WorkAttr> getAttrsByWorkId(Long workId) {
		return workAttrMapper.getWorkAttrByWorkId(workId);
	}
}
